import json
import requests
import time
import bs4
import re
import random
#from PIL import Image
#from io import BytesIO
import execjs
from fake_useragent import UserAgent

'''
#START  易码平台相关函数
'''
#幕布项目编号
Project__ID='5823'
#易码平台Token
My_Token='your token'
#获取手机号码API接口
API_Get_Phone_Num='http://api.fxhyd.cn/UserInterface.aspx?action=getmobile&token='+My_Token+'&itemid='+Project__ID

#获取短信内容API
#输入：手机号码
#返回：获取短信内容API
def Ret_API_Get_Msg(ph_num):
    return 'http://api.fxhyd.cn/UserInterface.aspx?action=getsms&token='\
           +My_Token+'&itemid='\
           +Project__ID+'&mobile='\
           +ph_num+'&release=1'

#获取手机号码
def Get_Phone_Num():
    print('正在获取注册手机号码。。。')
    res=str(requests.get(API_Get_Phone_Num).content, encoding = "utf-8")
    #print(res)
    if res[0:7]=="success":
        ss=res.split('|')
        print('手机号码获取成功：',ss[1])
        print("Get Phone Number:"+ss[1])
        return ss[1]
    else:
        print('手机号码获取失败：请重试')
        return  None


#获取短信内容
#每隔3s查询一次
#输入：api：请求API链接;timeout：超时时间
#返回：短信验证码
def Get_Msg_Content(api,timeout=20):
    t=0
    while(t<timeout):
        time.sleep(3)
        print('检查是否获取验证码短信（第 '+str(t+1)+' 次）：')
        print('Try To Get Verity Code:')
        res=str(requests.get(api).content, encoding = "utf-8")
        if(res=='3001'):
            print('检查结果，无短信，错误码：',res)
            print('Result:','Err:',res)
            t+=1
            continue
        if(res[0:7]=='success'):
            print('获取短信成功，内容：',res)
            print('Result:',res)
            code_compile1 = re.compile(r'(\d{6})')  # 匹配验证码
            code = re.findall(code_compile1, str(res))
            if(len(code)==1):
                print('检索到验证码为：',code[0])
                return code[0]          #返回验证码
            break
    print('检查短信超时，请重试！')
    return None

'''
#END    易码平台相关
'''

'''
#START    IP代理
'''
Header_Proxy={
    "Accept":"text/html,application/xhtml+xml,application/xml;",
    "Accept-Encoding":"gzip, deflate, sdch",
    "Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6",
    "Referer":"http://www.xicidaili.com",
    "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    }


URL_Proxy='http://www.xicidaili.com/nn/1'

#获取请求时间小于1s的IP代理
def Proxy_Get():
    res = requests.get(URL_Proxy, headers=Header_Proxy).text
    soup = bs4.BeautifulSoup(res, 'html.parser')
    data = soup.table.find_all("td")
    ip_compile = re.compile(r'<td>(\d+\.\d+\.\d+\.\d+)</td>')  # 匹配IP
    port_compile = re.compile(r'<td>(\d+)</td>')  # 匹配端口
    type_compile = re.compile(r'HTTP[S]?')  # 匹配连接类型
    time_compile = re.compile(r'"\d+\.\d+秒"')
    time_compile1 = re.compile(r'\d+\.\d+')  # 匹配详细时间
    ip = re.findall(ip_compile, str(data))  # 获取所有IP
    port = re.findall(port_compile, str(data))  # 获取所有端口
    con_type = re.findall(type_compile, str(data))  # 获取连接类型
    time = re.findall(time_compile, str(data))
    time1 = [''.join(re.findall(time_compile1, i)) for i in time]  # 获取所有时间
    ip_port = ['://'.join(j) for j in
               zip(con_type, [":".join(i) for i in zip(ip, port)])]  # 组合IP+端口，如：https"//115.112.88.23:8080
    # 新建一个空列表，存储时间小于1S的代理
    List_Proxy = []
    for t in range(0, int(len(time1) / 2)):
        if (float(time1[t*2]) < 1 and float(time1[t*2 + 1]) < 1):
            # print(time1[t],time1[t+1])
            dict_info={'id':t}
            dict_info['type']=con_type[t].lower()
            dict_info['time_speed']=time1[t*2]
            dict_info['time_con'] = time1[t*2+1]
            dict_info['adress']=ip_port[t].lower()
            dict_info['ip']=ip[t]
            List_Proxy.append(dict_info)
    print('Get Proxy Count(time<1s):',len(List_Proxy))
    return  List_Proxy

Header_Check={
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'max-age=0',
    'Connection':'keep-alive',
    'Cookie': '_gauges_unique_hour=1; _gauges_unique_day=1; _gauges_unique_month=1; _gauges_unique_year=1; _gauges_unique=1',
    'Host': 'httpbin.org',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
}

def Proxy_Check(one_proxy):
    try:
        print('Check Proxy:', one_proxy['adress'])
        res=requests.get(
            one_proxy['type']+'://httpbin.org/ip'
            ,proxies={one_proxy['type']:one_proxy['adress']}
            ,headers=Header_Check
            ,timeout=5
        ).json()
        #print(res)
        if(res['origin']==one_proxy['ip']):
            return True
    except requests.ConnectionError:
        #print("err1")
        return False
    except json.decoder.JSONDecodeError:
        #print("err2")
        return  False
    except requests.exceptions.ReadTimeout:
        #print("err3")
        return False



#测试代理
#list_dict_proxy= Proxy_Get()
#for ldp in list_dict_proxy:
#    print(Proxy_Check(ldp))

'''
#END    IP代理
'''


#获取JS文件
def Get_JS(filename):
    # f = open("D:/WorkSpace/MyWorkSpace/jsdemo/js/des_rsa.js",'r',encoding='UTF-8')
    f = open(filename, 'r', encoding='UTF-8')
    line = f.readline()
    htmlstr = ''
    while line:
        htmlstr += line
        line = f.readline()
    f.close()
    return htmlstr
#测试JS文件
#ctx = execjs.compile(Get_JS('t.js'))
#print(ctx.call("veritycode"))

'''
#START    注册操作
'''
#GA1提交参数
GA_PayLoad = {
    'v': '1',
    '_v': 'j72',
    'a': '112342758',
    't': 'pageview',
    '_s': '1',
    'dl': 'https://mubu.com/inv/1997126',
    'ul': 'zh-cn',
    'de': 'UTF-8',
    'dt': '幕布：可以一键生成思维导图的大纲笔记工具',
    'sd': '24-bit',
    'sr': '1920x1080',
    'vp': '957x938',
    'je': '0',
    '_u': 'IEBAAEAB~',
    'jid': '1222810002',
    'gjid': '1976461140',
    'cid': '1440707185.1544512943',
    'tid': 'UA-77727571-1',
    '_gid': '1835056365.1544512943',
    '_r': '1',
    'z': '1146203863'
}
#GA1请求头
GA_Header={
        'referer':'https://mubu.com/inv/1997126',
        'user-agent':''
}

def GA_Request():
    GA_PayLoad['a']=str(random.randint(100000000,10000000000))  #设置随机参数a
    GA_PayLoad['z'] = str(random.randint(100000000, 10000000000))  # 设置随机参数缓存大小：z
    res=requests.get(url='https://www.google-analytics.com/r/collect',headers=GA_Header,params=GA_PayLoad)
    print('GA时间执行完成，响应码：',res.status_code)



#GA_Request()


#获取随机请求头文件  user-agent随机选择
def MUBU_Header():
    #ua = UserAgent()
    #ua.random
    GA_Header['user-agent']=UserAgent().random
    GA_PayLoad['vp'] = str(random.randint(500, 1800)) + 'x' + str(random.randint(300, 938))  # 设置随机屏幕大小参数vp
    print('获取随机User-Agent：',GA_Header['user-agent'])
    return {
        #'[authority]':'mubu.com',
        #'[method]':'GET',
        #'[path]':'/inv/1997126',
        #'[scheme]':'https',
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "accept-encoding": "gzip, deflate, br",
        "accept-language": "zh-CN,zh;q=0.9",
        #'cookie':'reg_entrance=https%3A%2F%2Fmubu.com%2Finv%2F1997126',
        "user-agent":GA_Header['user-agent'],
        "upgrade-insecure-requests": "1"
    }
#邀请地址
URL_Invitation_Adress1='/inv/1997126'
URL_Invitation_Adress2='/inv/1997126'
#推荐地址
URL_Recommand_Address='https://mubu.com'+URL_Invitation_Adress1
#注册地址
URL_Register_Address='https://mubu.com/reg'
#获取短信验证码地址
URL_GetMsg_Address='https://mubu.com/api/reg/send_sms_code'
#Submit URL
URL_Submit_Address='https://mubu.com/api/reg/submit'

#根据电话号码获取验证码
def Register(phone_num):
    print('幕布自动注册程序开始执行，参数初始化中。。。')
    s=requests.session()            #创建会话
    s.headers=MUBU_Header()
    ctx = execjs.compile(Get_JS('t.js'))      #加载JS文件
    jar = requests.cookies.RequestsCookieJar()
    jar.set('reg_entrance', 'https://mubu.com'+URL_Invitation_Adress2, domain='mubu.com', path='/')
    s.cookies=jar       #设置Cookie
    print('初始化完成，开始注册！')
    print('Start Register...')
    # 请求邀请地址
    print('正在根据邀请地址（'+URL_Recommand_Address+'）获取 Cookie Session。。。')
    print('Load Invitation Adress To Get Cookie Session...')
    s.get(URL_Register_Address)
    print('获取 Cookie Session：',s.cookies.get('SESSION'))
    print('Get Cookie Session:',s.cookies.get('SESSION'))

    start_time=str((int)(time.time()))      #获取10位时间
    starttime1 = ctx.call("starttime")
    print('获取开始时间：',start_time)
    print('Get Start Time:',start_time)
    print('获取开始时间(JS 16)：', starttime1)
    print('Get Hex Start Time:',starttime1)
    _ga=str(random.randint(100000000,10000000000))
    _ga_str='GA1.2.'+_ga+'.'+start_time
    GA_PayLoad['cid']=_ga+'.'+start_time
    print('获取随机GA参数 _ga：',_ga_str)
    print('Get Random _ga:',_ga,_ga_str)
    _gid=str(random.randint(100000000,10000000000))
    _gid_str='GA1.2.'+_gid+'.'+start_time
    GA_PayLoad['_gid'] = _gid+'.'+start_time
    print('获取随机GA参数 _gat：',_gid_str)
    print('Get Random _gid:',_gid_str)
    GA_PayLoad['jid'] = str(random.randint(100000000, 10000000000))  # 设置随机参数jid
    GA_PayLoad['gjid'] = str(random.randint(100000000, 10000000000))  # 设置随机参数gjid
    GA_Request()                            #请求GA
    print('正在重置请求头以及Cookie用于请求注册地址（'+URL_Register_Address+'）')
    print('Reset Request Header And Cookie To Register:')
    #重新设置请求头 cookie
    # s.headers['cookie']='SESSION='+s.cookies.get('SESSION') +\
    #                     ';_ga='+_ga_str+ \
    #                     ';_gid='+_gid_str+ \
    #                     ';_gat=1'
    #s.headers['[path]']='/reg'
    s.headers['referer']='https://mubu.com/inv/1997126'
    jar.set('reg_entrance', 'https://mubu.com/Freg' + URL_Invitation_Adress2, domain='mubu.com', path='/')
    jar.set('_ga',_ga_str,domain='.mubu.com',path='/')
    jar.set('_gid',_gid_str, domain='.mubu.com', path='/')
    jar.set('_gat', '1', domain='.mubu.com', path='/')
    s.cookies=jar
    print('正在请求注册地址获取 [send-id] 值。。。')
    print('Load Register Adress To Get Send ID...')
    time.sleep(1)
    res=s.get(URL_Register_Address)       #请求注册地址
    soup=bs4.BeautifulSoup(res.text,'html.parser')
    soup=soup.select('#send-id')[0]
    sendid_compile = re.compile(r'value=\"(\S+)\"')  # 匹配send-id
    send_id = re.findall(sendid_compile, str(soup))[0]
    print('获取 send-id：',send_id)
    print('Get Send ID:',send_id)
    #重新设置cookie  获取验证码
    #获取focus id 和 prepare id
    time.sleep(1)
    focus_id=ctx.call("focusid",send_id)
    print('根据JS文件获取Cookie[reg_focusId]字段：',focus_id)
    print('Get Focus ID:',focus_id)
    time.sleep(1)
    prepare_id = ctx.call("prepareid", send_id,starttime1)
    print('根据JS文件获取Cookie[reg_prepareId]字段：', prepare_id)
    print('Get Focus Prepare ID::', prepare_id)
    GA_Header['referer']='https://mubu.com/reg'
    GA_PayLoad['dl']='https://mubu.com/reg'
    GA_PayLoad['dt']='注册幕布帐号'
    GA_PayLoad['jid']=''
    GA_PayLoad['gjid']=''
    GA_Request()                                                                # 请求GA
    print('正在重置请求头以及Cookie用于请求短信验证码地址（'+URL_GetMsg_Address+'）')
    print('Reset Request Header And Cookie To Get Verity Msg:')
    # s.headers['cookie'] +=';reg_focusId='+focus_id
    # s.headers['cookie'] += ';reg_prepareId=' + prepare_id
    s.headers['origin']='https://mubu.com'
    s.headers['referer']='https://mubu.com/reg'
    #s.headers['[path]']='/api/reg/send_sms_code'
    #s.headers['[method]'] = 'POST'
    s.headers['accept']='application/json, text/javascript, */*; q=0.01'
    s.headers['content-length']='61'
    s.headers['content-type']='application/x-www-form-urlencoded; charset=UTF-8'
    s.headers['x-requested-with']='XMLHttpRequest'
    jar.set('reg_entrance', 'https://mubu.com/reg', domain='mubu.com', path='/')
    jar.set('reg_focusId', focus_id, domain='mubu.com', path='/')
    jar.set('reg_prepareId',prepare_id , domain='mubu.com', path='/')
    s.cookies=jar
    payload={'sendId':send_id,
             'phone':phone_num}
    res=s.post(URL_GetMsg_Address,data=payload)
    try:
        json_msg=json.loads(res.text,encoding='utf-8')
        if(json_msg['code'])==0:
            print('获取验证码成功，回执信息：',json_msg)
            print('Request Verity Msg Success:',json_msg)
            return [0,s]
        else:
            print('获取验证码失败，原因：')
            print('Request Verity Msg Fail:',json_msg['msg'],json_msg['data'])
            return [1,None]
    except:
        print('获取验证码失败，原因：返回数据有误！')
        return [1,None]

#随机字母表
List_Char=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
                 ,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#随机数字表
List_Num=['0','1','2','3','4','5','6','7','8','9']

#提交注册申请
#sen：会话
#验证码
def Submit(sen,ph,code):
    #sen.headers['[path]']='/api/reg/submit'
    print('正在获取随机昵称密码（登录帐号为手机号码）。。。')
    RD_User_Name=''.join(random.sample(List_Char, 8))+''.join(random.sample(List_Num, 4))
    RD_User_PWD = ''.join(random.sample(List_Char, 8)) + ''.join(random.sample(List_Num, 6))
    sen.headers['content-length']='66'
    payload = {
        'name': RD_User_Name,
        'phone': ph,
        'code': code,
        'password':RD_User_PWD
    }
    res=sen.post(URL_Submit_Address,data=payload)
    print(sen.cookies)
    print(sen.cookies.get('reg_inv_id'))
    print(res.text)
    print(res.headers)

    GA_Header['referer'] = 'https://mubu.com/welcome'
    GA_PayLoad['dl'] = 'https://mubu.com/welcome'
    GA_PayLoad['dt'] = '欢迎来到幕布 - 幕布'
    GA_PayLoad['jid'] = str(random.randint(100000000, 10000000000))  # 设置随机参数jid
    GA_PayLoad['gjid'] = str(random.randint(100000000, 10000000000))  # 设置随机参数gjid
    GA_Request()  # 请求GA
    print('注册完成！')
    print('手机号码：',ph)
    print('用户呢称：',RD_User_Name)
    print('用户密码：',RD_User_PWD)
    print('Register Sucess!')

#Register('15543129624')
#print(''.join(random.sample(List_Char, 8)))

'''
#END    注册操作
'''


#print( requests.get('https://httpbin.org/ip', proxies={'https': 'https://113.108.242.36:47713'}).json())
#s = requests.session()
#s.proxies = {'https': 'https://222.171.251.43:40149'}
#print(s.get('https://httpbin.org/ip').json())


if __name__ == '__main__':
    ph=Get_Phone_Num()
    if ph:
        ss=Register(ph)
        if(ss[0]==0):
            code=Get_Msg_Content(Ret_API_Get_Msg(ph),100)
            time.sleep(3)
            if code:
                print('Get Verity Code:',code)
                print('Start Submit Register Request...')
                Submit(ss[1],ph,code)
